import { getsecond } from '../api/second';
const IndexModel = {
  namespace: 'second',

  state: {
    list: JSON.parse(localStorage.getItem('list'))
      ? JSON.parse(localStorage.getItem('list'))
      : [],
    detailsList: {},
  },

  effects: {
    *init(_, { call, put }) {
      const data = yield call(getsecond);
      yield put({
        type: 'GET_SECOND',
        list: data.data.RECORDS,
      });
    },
  },
  reducers: {
    GET_SECOND(state, action) {
      state.list = action.list;
      if (!JSON.parse(localStorage.getItem('list'))) {
        JSON.parse(localStorage.setItem('list', JSON.stringify(state.list)));
      }
      return {
        ...state,
      };
    },
    del(state, action) {
      console.log(action);
      state.list.forEach((item, index) => {
        if (item.id == action.payload.id) {
          state.list.splice(index, 1);
          localStorage.setItem('list', JSON.stringify(state.list));
        }
      });
      return {
        ...state,
      };
    },
    GET_DETAILSLIST(state, action) {
      JSON.parse(localStorage.getItem('list')).forEach((item, index) => {
        if (item.id == action.payload) {
          state.detailsList = item;
        }
      });
      return {
        ...state,
      };
    },
    CHANGE_LIST(state, action) {
      console.log(action);
      state.list.forEach((item, index) => {
        if (item.id == action.payload.id) {
          state.list[index] = action.payload;
          console.log(state.list);
          localStorage.setItem('list', JSON.stringify(state.list));
        }
      });
      return {
        ...state,
      };
    },
    ADD_LIST(state, action) {
      console.log(action);
      state.list.push(action.payload);
      localStorage.setItem('list', JSON.stringify(state.list));
      return {
        ...state,
      };
    },
  },
};

export default IndexModel;
